﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class DictController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        [AuthorizeFilter("Manage.Dict")]
        // GET: Manage/Dict
        public ActionResult List()
        {
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();
            ViewBag.Title = "数据字典";
            S_dicttypeService dicttypeservice = new S_dicttypeService();

            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Manage.Dict.Edit");

            //字典类别下拉框数据
            ViewBag.DicttypeList = dicttypeservice.GetSelectList();

            return View();
        }

        #endregion

        #region DictListJson

        /// <summary>
        /// 查询列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="s"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        [AuthorizeFilter("Manage.Dict")]
        public JsonResult DictListJson(int page, int rows, string s, string Dicttype, string sort, string order)
        {
            S_dicttypeService dicttypeservice = new S_dicttypeService();
            S_dictService dictService = new S_dictService();
            //K_medicationService medicationservice = new K_medicationService();

            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            var list = dictService.PageList(page, rows, s, Dicttype, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Code,
                Typecode = dicttypeservice.GetDicttypeName(p.Typecode) + "(" + p.Typecode + ")",
                p.Name_cn,
                p.Sort,
                p.Isdeleted,
                p.Remark,
                Updatetime = p.Updatetime.HasValue ? p.Updatetime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

        #region Edit

        [AuthorizeFilter("Manage.Dict")]
        public ActionResult Edit(int id)
        {
            S_dictService dictservice = new S_dictService();
            S_dicttypeService dicttypeservice = new S_dicttypeService();

            //默认字典分类
            var typecode = Request.QueryString["t"];

            var item = new S_dict
            {
                Typecode = typecode,
                Isdeleted = "0"
            };
            if (id > 0)
            {
                item = dictservice.Find(id);
                if (item == null)
                {
                    throw new HttpException(404, "Dict(id='" + id.ToString() + "') not found!");
                }
            }

            //类别下拉框数据
            ViewBag.DicttypeList = dicttypeservice.GetSelectList(item.Typecode);

            return View(item);
        }

        #endregion

        #region Save

        [AuthorizeFilter("Manage.Dict", ActionType.Ajax)]
        [ValidateInput(false)]
        public JsonResult Save(string json)
        {
            try
            {
                S_dictService dictservice = new S_dictService();

                JsonDataModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataModel>(json);

                S_dict dict = new S_dict
                {
                    Isdeleted = "0"
                };

                //如果是修改数据
                if (model.Id > 0)
                {
                    dict = dictservice.Find(model.Id);
                }
                //将Json数据赋值给Model对象
                model.SetModelData<S_dict>(dict);
                dictservice.Save(dict);
                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 重复验证

        [IgnoreAuthorizeFilter]
        public string ExistCheck(int id, string medicationcode)
        {
            return "yes";
            //return new S_dictService().Exist(id, medicationcode) ? "no" : "yes";
        }

        #endregion

        #region 删除

        [AuthorizeFilter("Manage.Dict", ActionType.Ajax)]
        public JsonResult Delete(string ids)
        {
            try
            {
                new S_dictService().DeleteById(ids);

                return Json(new AjaxResult("0", CSMSLang.Get("message_delete_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion
    }
}